package com.hopu.v1.service.admin.system.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.exception.NoLoginException;
import com.hopu.v1.mapper.admin.subject.SubjectMapper;
import com.hopu.v1.mapper.admin.system.StaffMapper;
import com.hopu.v1.pojo.common.PageData;
import com.hopu.v1.pojo.subject.Subject;
import com.hopu.v1.pojo.system.Organization;
import com.hopu.v1.pojo.system.Staff;
import com.hopu.v1.service.admin.system.OrganizationService;
import com.hopu.v1.service.admin.system.StaffService;
import com.hopu.v1.utils.JwtUtils;
import com.hopu.v1.vo.StaffVo;
import com.hopu.v1.vo.StaffVo2;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YwaiX
 * @since 2024-09-12
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements StaffService {

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private OrganizationService organizationService;

    @Override
    public void exportUsersToExcel(List<Staff> staffs, HttpServletResponse response) throws IOException {
        // 设置文件名
        String fileName = "users_" + System.currentTimeMillis() + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet("用户信息").head(Staff.class).build();
        writer.write(staffs, sheet);
        writer.finish();
    }

    /**
     * 获取员工列表-袁胡宇
     *
     * @param page
     * @return
     */
    @Override
    public PageData<StaffVo> selectAll(Page<Staff> page, Staff staffInfo) {
        List<Integer> organizationIds = null;
        if (staffInfo.getOrganizationId() != null) {
            organizationIds = organizationService.getOrganizationIds(staffInfo.getOrganizationId());
        }
        List<StaffVo> staffVoList = staffMapper.selectStaff((page.getCurrent() - 1) * page.getSize(), page.getSize(), staffInfo,organizationIds);
        Integer total = staffMapper.getTotal(staffInfo,organizationIds);
        //封装PageData
        PageData<StaffVo> pageData = new PageData<>((int) page.getPages(), (int) page.getSize(), total, staffVoList);
        return pageData;
    }

    @Override
    public String login(Staff staff) {
        Staff selectOne = staffMapper.selectOne(new LambdaQueryWrapper<Staff>().eq(Staff::getStaffNo, staff.getStaffNo()));
        if (selectOne == null) {
            throw new NoLoginException("工号ID错误！");
        }
        if (!selectOne.getPassword().equals(staff.getPassword())) {
            throw new NoLoginException("用户密码错误！");
        }
        System.out.println(selectOne.getStatus());
        if(selectOne.getStatus() == 0){
            throw new NoLoginException("用户账号已经被锁定，请联系管理员开通权限");
        }
        return JwtUtils.createToken(String.valueOf(selectOne.getId()));
    }

    /**
     * 修改员工
     *
     * @param staff
     */
    @Override
    public void update(Staff staff) {
        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Staff::getIdCard, staff.getIdCard());
        Staff staff2 = getOne(lambdaQueryWrapper);
        if (staff2 != null && !staff2.getStaffNo().equals(staff.getStaffNo())) {
            throw new BusinessException("身份证号不能重复");
        }
        LambdaUpdateWrapper<Staff> updateWrapper = new LambdaUpdateWrapper<>();
        if (StringUtil.isNullOrEmpty(staff.getStaffNo())) {
            throw new BusinessException("用户编号不能为空");
        }
        updateWrapper.eq(Staff::getStaffNo, staff.getStaffNo());

        // 使用 Lambda 表达式动态更新字段
        Optional.ofNullable(staff.getPhotoUrl()).ifPresent(photoUrl -> updateWrapper.set(Staff::getPhotoUrl, photoUrl));
        Optional.ofNullable(staff.getRealName()).ifPresent(name -> updateWrapper.set(Staff::getRealName, name));
        Optional.ofNullable(staff.getPassword()).ifPresent(password -> updateWrapper.set(Staff::getPassword, password));
        Optional.ofNullable(staff.getGender()).ifPresent(gender -> updateWrapper.set(Staff::getGender, gender));
        Optional.ofNullable(staff.getIdCard()).ifPresent(idCard -> updateWrapper.set(Staff::getIdCard, idCard));
        Optional.ofNullable(staff.getDateOfBirth()).ifPresent(dob -> updateWrapper.set(Staff::getDateOfBirth, dob));
        Optional.ofNullable(staff.getPhone()).ifPresent(phone -> updateWrapper.set(Staff::getPhone, phone));
        Optional.ofNullable(staff.getOrganizationId())
                .ifPresent(orgId -> updateWrapper.set(Staff::getOrganizationId, orgId));
        Optional.ofNullable(staff.getJobName()).ifPresent(jobName -> updateWrapper.set(Staff::getJobName, jobName));
        Optional.ofNullable(staff.getStatus()).ifPresent(status -> updateWrapper.set(Staff::getStatus, status));
        Optional.ofNullable(staff.getSalary()).ifPresent(salary -> updateWrapper.set(Staff::getSalary, salary));
        /*Optional.ofNullable(staff.getUpdateBy()).ifPresent(updateBy -> updateWrapper.set(Staff::getUpdateBy, updateBy));
        Optional.ofNullable(staff.getUpdateTime()).ifPresent(updateTime -> updateWrapper.set(Staff::getUpdateTime, updateTime));

        Optional.ofNullable(staff.getIsFirstLogin()).ifPresent(firstLogin -> updateWrapper.set(Staff::getIsFirstLogin, firstLogin));
*/
        update(updateWrapper);
    }

    /**
     * 根据员工编号查询员工信息
     *
     * @param staffNo
     * @return
     */
    @Override
    public StaffVo staffInfo(String staffNo) {
        System.out.println(staffNo);
        //查询个人
        Staff staff = staffMapper.selectOne(new LambdaQueryWrapper<Staff>().eq(Staff::getStaffNo, staffNo));
        //查询组织a
        Organization organization = organizationService.getOrganizationById(staff.getOrganizationId());
        return new StaffVo(staff, organization.getOrganizationName());
    }

    /**
     * 添加员工
     *
     * @param staff
     */
    @Override
    public void add(Staff staff) {
        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Staff::getIdCard, staff.getIdCard());
        if (getOne(lambdaQueryWrapper) != null) {
            throw new BusinessException("身份证号已存在");
        }

        LambdaQueryWrapper<Staff> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(Staff::getStaffNo, staff.getStaffNo());
        if (getOne(lambdaQueryWrapper2)!=null) {
            throw new BusinessException("员工工号不能重复");
        }
        LambdaQueryWrapper<Staff> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3.eq(Staff::getPhone, staff.getPhone());
        if (getOne(lambdaQueryWrapper3)!= null) {
            throw new BusinessException("手机号不能重复");
        }
        //插入用户
        save(staff);
    }

    @Override
    public void updateInfo(String staffNo, String password, String phone, String photoUrl, String realName, String gender) {
        staffMapper.updateInfo(staffNo, password, phone,photoUrl,realName,gender);
    }

    /**
     * 修改员工状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Integer id, Integer status) {
        Staff staff = new Staff();
        staff.setId(id);
        staff.setStatus(status);
        baseMapper.updateById(staff);
    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void deleteStaff(List<Integer> ids) {
        baseMapper.deleteByIds(ids);
    }

    /**
     * 获取最新一条员工编号
     */
    @Override
    public String selectStaffNo(String staffNo) {
        return staffMapper.selectStaffNo(staffNo);
    }

    @Override
    public List<StaffVo2> getStaffsWithSubjects() {
        //初始化员工列表
        List<Staff> staffs = staffMapper.selectList(null);

        List<StaffVo2> staffVo2s = new ArrayList<>();

        for (Staff staff : staffs) {

            StaffVo2 staffVo2 = new StaffVo2();
            staffVo2.setStaff(staff);

            List<Subject> subjects = subjectMapper.getSubjectByStaffId(staff.getId());
            List<String> subjectNames = subjects.stream().map(Subject::getSubjectName).collect(Collectors.toList());
            staffVo2.setSubjectNames(subjectNames);
            staffVo2s.add(staffVo2);
        }

        return staffVo2s;
    }
}

